<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 验证码控制器
 * @property ApiOutput $apiOutput
 */
class Captcha extends CI_Controller {
	
	const IMG_SESSION_KEY = 'imgcode';
	
	public function __construct(){
		if(!isset($_SESSION)){
			session_start();
		}
		parent::__construct();
	}

	/**
	 * 发送验证码
	 * 传入参数:手机号码
	 */
	public function send(){
		$input = check_input ( $_REQUEST, array ('phone','code') );
		if (empty ( $input )) {
			$this->apiOutput->error ( '参数错误', $this->apiOutput->eParam );
		}
		if (empty ( $input ['phone'] )) {
			$this->apiOutput->error ( '请输入正确的手机号码', - 1 );
		}
		if (empty ( $_SESSION [self::IMG_SESSION_KEY] ) || strtolower ( $input ['code'] ) != strtolower ( $_SESSION [self::IMG_SESSION_KEY] )) {
			$this->apiOutput->error ( '图形验证码错误', - 2 );
		}
		unset ( $_SESSION [self::IMG_SESSION_KEY] );

		$this->load->library ( 'PhoneCaptcha' );
		try {
			PhoneCaptcha::send ( $input ['phone'] ); // 发送验证码
		} catch ( Exception $e ) {
			$msg = $e->getMessage ();
			$this->apiOutput->error ( $msg, - 3 );
		}

		$this->apiOutput->put ( 'msg', '短信发送成功!' )->out ();
	}
	
	
	/**
	 * 获取验证码图片
	 */
	public function img(){
		$config = array(
				'width'	=>	115,
				'height'=>	46,
				'codeLen'=>	4,
				'fontSize'=>24,
				'sessionKey'=>self::IMG_SESSION_KEY,
		);
		$this->load->library('ImgCaptcha', $config,'ImgCaptcha');
		$this->ImgCaptcha->show();
	}
	
	
	
	
	
	
	
// 	/**
// 	 * 验证令牌
// 	 * @return boolean
// 	 */
// 	private function checkToken($time,$phone,$token){
// 		if( defined('IS_TEST') && IS_TEST  ){
// 			return true;
// 		}
// 		$num = $time - $phone*55;
// 		$num = round( abs(sin($num)) , 6 )+0.141592;
// 		$check = md5($num);
// 		return strcasecmp($token, $check)===0 ? TRUE : FALSE;
// 	}
	
// 	public function check(){
// 		$input = check_input($_REQUEST,array('phone','captcha'));
// 		if( empty($input) ){
// 			$this->apiOutput->error('参数错误',$this->apiOutput->eParam);
// 		}
// 		if( empty($input['phone']) ){
// 			$this->apiOutput->error('请输入正确的手机号码',-1);
// 		}
// 	}
}